package com.lh.nk;

import java.util.Stack;

/**
 * @author: linghao
 * @since: 2023/1/19
 * 描述
 * 给出一个仅包含字符'(',')','{','}','['和']',的字符串，判断给出的字符串是否是合法的括号序列
 * 括号必须以正确的顺序关闭，"()"和"()[]{}"都是合法的括号序列，但"(]"和"([)]"不合法。
 */
public class 有效括号序列NC52 {

    public static void main(String[] args) {
        System.out.println(isValid("()"));
    }

    public static boolean isValid (String s) {
        // write code here
        Stack<Character> stack = new Stack<>();
        for(int i = 0;i<s.length();i++){
            char c = s.charAt(i);
            switch (c){
                case '(':
                case '{':
                case '[':
                    stack.push(c);
                    break;
                case ')':
                    if(stack.isEmpty() || stack.peek() != '('){
                        return false;
                    }
                    stack.pop();
                    break;
                case '}':
                    if(stack.isEmpty() || stack.peek() != '{'){
                        return false;
                    }
                    stack.pop();
                    break;
                case ']':
                    if(stack.isEmpty() || stack.peek() != '['){
                        return false;
                    }
                    stack.pop();
                    break;
            }
        }
            return stack.isEmpty();
    }
}
